﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class MoveComponent : MonoBehaviour
{
	public delegate void Callback();
	public Callback finishedMove;

	public float speed = 1f;

	private Quaternion wantedRot;
	private Transform trans;
	private List<Vector3> path = null;

	private void Awake()
	{
		trans = transform;
	}

	private void Update()
	{
		if (path != null && path.Count > 0)
		{
			Vector3 direction = (path[0] - trans.position).normalized;

			if (direction != Vector3.zero)
			{
				wantedRot = Quaternion.LookRotation(Vector3.forward, direction);
			}

			if (Vector3.Dot(direction, path[0] - (trans.position + direction * speed * Time.deltaTime)) <= 0f)
			{
				trans.position = path[0];
				path.RemoveAt(0);
			}
			else
			{
				trans.position += direction * speed * Time.deltaTime;
			}

			if (path.Count == 0 && finishedMove != null)
			{
				finishedMove();
			}
		}

		if (Quaternion.Angle(trans.rotation, wantedRot) % 180 > 0.1f)
		{
			trans.rotation = Quaternion.Lerp(trans.rotation, wantedRot, 10f * Time.deltaTime);
		}
	}

	public void MoveToPosition(Vector3 _pos)
	{
		path = new List<Vector3>();
		path.Add(_pos);
	}
	
	public void FollowPath(List<Vector3> _path)
	{
		path = _path;
	}

	public void LookAt(Vector3 _towards)
	{
		Debug.Log("Look At " + _towards);
		wantedRot = Quaternion.LookRotation(Vector3.forward, _towards - trans.position);
	}
}
